package constant.milk.periodapp.memo;

import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import constant.milk.periodapp.R;
import constant.milk.periodapp.SuperActivity;
import constant.milk.periodapp.bean.MemoData;
import constant.milk.periodapp.database.DBSelectQuery;
import constant.milk.periodapp.database.DbDeleteQuery;
import constant.milk.periodapp.database.DbInsertQuery;
import constant.milk.periodapp.database.DbUpdateQuery;
import constant.milk.periodapp.dialog.MilkCheckDialog;
import constant.milk.periodapp.dialog.MilkDayDialog;
import constant.milk.periodapp.dialog.MilkDayDialog.DateCallBank;
import constant.milk.periodapp.dialog.MilkYesNoDialog;
import constant.milk.periodapp.util.MilkUtil;

public class MemoInfoActivity extends SuperActivity
{
	public static final String MEMO_FLAG = "MEMO_FLAG";
	public static final String MEMO_ID = "MEMO_ID";
	
	public static final int INFO = 0;
	public static final int INSERT = 1;
	public static final int UPDATE = 2;
	
	private TextView backTextView;
	private TextView titleTextView;
	
	private TextView dateTextView;
	private TextView updateTextView;
	private TextView deleteTextView;
	private EditText memoEditText;
	
	private TextView saveTextView;
	
	private int flag;
	private int memoFlag;
	
	private DBSelectQuery select;
	
	private int year;
	private int month;
	private int day;
	
	private int id;
	
	private MilkYesNoDialog yesNoDialog;
	private MilkCheckDialog checkDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.memo_info_activity);
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		backTextView = (TextView) findViewById(R.id.memoInfoBackTextView);
		titleTextView = (TextView) findViewById(R.id.memoInfoTitleTextView);
		
		dateTextView = (TextView) findViewById(R.id.memoInfoDateTextView);
		updateTextView = (TextView) findViewById(R.id.memoInfoUpdateTextView);
		deleteTextView = (TextView) findViewById(R.id.memoInfoDeleteTextView);
		memoEditText = (EditText) findViewById(R.id.memoInfoMemoEditText);
		
		saveTextView = (TextView) findViewById(R.id.memoInfoSaveTextView);
	}

	@Override
	protected void setOnClick()
	{
		backTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		dateTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				MilkDayDialog dialog = new MilkDayDialog(superContext, new DateCallBank()
				{
					@Override
					public void getDate(int setYear, int setYonth, int seyDay)
					{
						year = setYear;
						month = setYonth;
						day = seyDay;
						
						Calendar cal = Calendar.getInstance();
						
						cal.set(year, month, day);
						
						dateTextView.setText(MilkUtil.getDateCom(year, month+1, day) + 
								" " + MilkUtil.getWeekDay(cal.get(Calendar.DAY_OF_WEEK)));
					}
				}, year, month, day);
				
				dialog.show();
			}
		});
		
		updateTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				flag = UPDATE;
				
				dateTextView.setClickable(true);
				titleTextView.setText("메모 수정");
				updateTextView.setVisibility(View.GONE);
				deleteTextView.setVisibility(View.VISIBLE);
				saveTextView.setVisibility(View.VISIBLE);
				
				memoEditText.setFocusableInTouchMode(true);
				memoEditText.setFocusable(true);
				memoEditText.setClickable(true);
				memoEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
				memoEditText.requestFocus();
				memoEditText.setSelection(memoEditText.length());
				
				InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); 
				//키보드를 띄운다.
				imm.showSoftInput(memoEditText, 0);
			}
		});
		
		deleteTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "확인", "메모를 삭제 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						setDeleteData(id);
						
						setData();
						
						yesNoDialog.dismiss();
						
						setResult(Activity.RESULT_OK);
						finish();
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		saveTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (flag == INSERT)
				{
					if (setInsertData())
					{
						checkDialog = new MilkCheckDialog(superContext, "확인", "데이터 저장에 성공 하였습니다.",
								new View.OnClickListener()
								{
									@Override
									public void onClick(View v)
									{
										checkDialog.dismiss();
										setResult(Activity.RESULT_OK);
										finish();
									}
								});
						
						checkDialog.show();
					}
					else
					{
						checkDialog = new MilkCheckDialog(superContext, "확인", "데이터 저장에 실패 하였습니다.",
								new View.OnClickListener()
								{
									@Override
									public void onClick(View v)
									{
										checkDialog.dismiss();
									}
								});
						checkDialog.show();
					}
				}
				else if (flag == UPDATE)
				{
					if (setUpdateData())
					{
						checkDialog = new MilkCheckDialog(superContext, "확인", "데이터 수정에 성공 하였습니다.",
								new View.OnClickListener()
								{
									@Override
									public void onClick(View v)
									{
										checkDialog.dismiss();
										setResult(Activity.RESULT_OK);
										finish();
									}
								});
						checkDialog.show();
					}
					else
					{
						checkDialog = new MilkCheckDialog(superContext, "확인", "데이터 수정에 실패 하였습니다.",
								new View.OnClickListener()
								{
									@Override
									public void onClick(View v)
									{
										checkDialog.dismiss();
									}
								});
						checkDialog.show();
					}
					
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		select = new DBSelectQuery(superContext, superDb);
		
		Intent intent = getIntent();
		flag = intent.getIntExtra(MEMO_FLAG, 0);
		id = intent.getIntExtra(MEMO_ID, -1);
		memoFlag = intent.getIntExtra(MemoListActivity.MEMO_LIST_FLAG, MemoListActivity.ALL);
		
		Calendar cal = Calendar.getInstance();
		
		if (flag == INFO)
		{
			dateTextView.setClickable(false);
			titleTextView.setText("메모");
			updateTextView.setVisibility(View.VISIBLE);
			deleteTextView.setVisibility(View.VISIBLE);
			saveTextView.setVisibility(View.GONE);
			
			MemoData data = select.getMemoId(id);
			
			cal.set(data.getYear(), data.getMonth(), data.getDay());
			
			memoEditText.setText(data.getMemo());
			memoEditText.setFocusableInTouchMode(false);
			memoEditText.setFocusable(false);
			memoEditText.setClickable(false);
			memoEditText.setInputType(0);
			
			memoEditText.clearFocus();
		}
		else if (flag == INSERT)
		{
			dateTextView.setClickable(true);
			titleTextView.setText("메모 추가");
			updateTextView.setVisibility(View.INVISIBLE);
			deleteTextView.setVisibility(View.INVISIBLE);
			saveTextView.setVisibility(View.VISIBLE);
			
			memoEditText.setText("");
			memoEditText.setFocusableInTouchMode(true);
			memoEditText.setFocusable(true);
			memoEditText.setClickable(true);
			memoEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
			memoEditText.requestFocus();
			
			int year = intent.getIntExtra(MemoListActivity.MEMO_YEAR, cal.get(Calendar.YEAR));
			int month = intent.getIntExtra(MemoListActivity.MEMO_MONTH, cal.get(Calendar.MONTH));
			int day = intent.getIntExtra(MemoListActivity.MEMO_DAY, cal.get(Calendar.DAY_OF_MONTH));
			
			cal.set(year, month, day);
			
			new Handler().postDelayed(new Runnable()
			{
				@Override
				public void run()
				{
					InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); 
					//키보드를 띄운다.
					imm.showSoftInput(memoEditText, 0);
				}
			}, 100);
		}
		else
		{
			dateTextView.setClickable(true);
			titleTextView.setText("메모 수정");
			updateTextView.setVisibility(View.INVISIBLE);
			deleteTextView.setVisibility(View.VISIBLE);
			saveTextView.setVisibility(View.VISIBLE);
			
			MemoData data = select.getMemoId(id);
			
			cal.set(data.getYear(), data.getMonth(), data.getDay());
			
			memoEditText.setText(data.getMemo());
			memoEditText.setFocusableInTouchMode(true);
			memoEditText.setFocusable(true);
			memoEditText.setClickable(true);
			memoEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
			memoEditText.requestFocus();
			memoEditText.setSelection(memoEditText.length());
			
			new Handler().postDelayed(new Runnable()
			{
				@Override
				public void run()
				{
					InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); 
					//키보드를 띄운다.
					imm.showSoftInput(memoEditText, 0);
				}
			}, 100);
		}
		
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		day = cal.get(Calendar.DAY_OF_MONTH);
		
		cal.set(year, month, day);
		
		dateTextView.setText(MilkUtil.getDateCom(year, month+1, day) + 
				" " + MilkUtil.getWeekDay(cal.get(Calendar.DAY_OF_WEEK)));
	}
	
	private boolean setInsertData()
	{
		DbInsertQuery query = null;
		
		try
		{
			query = new DbInsertQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("memo", memoEditText.getText().toString());
			map.put("year", year + "");
			map.put("month", month + "");
			map.put("day", day + "");
			
			query.setMemo(map);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setUpdateData()
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("memo", memoEditText.getText().toString());
			map.put("year", year + "");
			map.put("month", month + "");
			map.put("day", day + "");
			
			query.setMemoUpdate(id, map);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setDeleteData(int id)
	{
		DbDeleteQuery query = null;
		
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			query.setMemoDelete(id);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
}
